How do i create a function, which takes one parameter - a number, and returns the sum of numbers from 1 -> number - without creating an infinite loop?
Example:
function(100)
= 5050
Ive come as far as creating a finite for loop as so:
let sum = 0
for (let i = 1; i <= 100; i++) {
sum = sum + i;
//thanks in advance
Well, it looks like you've got the basic premise sussed out for 1 to 100 - you're cycling through to the value and summing up. To put it into a bit of a nicer format:
const n = 100;
console.log(GetSumTo(n))
function GetSumTo(x) {
var sum = 0;
for (var i = 1; i <= x; i++) {
sum = sum + i;
}
return sum;
}
Another option would be do it recursively:
const n = 100;
console.log(RecursiveSum(n, 0));
function RecursiveSum(val, sum) {
if (val > 1) {
sum = val + RecursiveSum(val - 1, sum);
}
else {
sum = val;
}
return sum;
}
However, these can be time consuming when dealing with large values. Using a fancy bit of maths (explained here better than I can explain it: https://math.stackexchange.com/questions/1100897/sum-of-consecutive-numbers), we can find that the sum of consecutive numbers can be calculated with an easier formula: (n(n + 1))/2
Meaning we can just write a function to do that and save execution time:
const n = 100;
console.log(QuickSum(n));
function QuickSum(n) {
var sum = n + 1;
sum = sum * n;
sum = sum / 2; //You could shrink the calculation to sum = (n * (n + 1)) / 2 I just did it over a few lines for readability
return sum;
};
None of these options result in an infinite loop.